package com.mida.bms.report.service.impl;


import com.mida.bms.report.entity.DocStructTemplateAuth;
import com.mida.bms.report.entity.DocStructTemplateAuthSpace;
import com.mida.bms.report.entity.DocUseSpaceConsumer;
import com.mida.bms.report.entity.DocUseSpaceUnit;
import com.mida.bms.report.mapper.DocStructTemplateAuthMapper;
import com.mida.bms.report.mapper.DocStructTemplateAuthSpaceMapper;
import com.mida.bms.report.mapper.DocUseSpaceConsumerMapper;
import com.mida.bms.report.mapper.DocUseSpaceUnitMapper;
import com.mida.bms.report.service.DocStructTemplateAuthSpaceService;
import com.mida.bms.report.service.SoidService;
import com.mida.bms.report.vo.*;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import com.mida.tool.common.utils.CharTransFormUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.mida.tool.common.result.BaseResult.*;

/**
 * @author ：wang xiao le
 * @description：TODO 模板报告授权空间
 * @date ：2021/3/30 14:45
 */
@Service
@Slf4j
@Transactional(value = "docTxManager", rollbackFor = Exception.class)
public class DocStructTemplateAuthSpaceServiceImpl implements DocStructTemplateAuthSpaceService {
    /**
     * 通用启用状态编码---未启用
     */
    public static final Long CLOSESTATUS = 150L;
    public static final String ERROR_MESSAGE_0001 = "批量处理失败，请联系管理员";
    @Autowired
    private DocStructTemplateAuthSpaceMapper docStructTemplateAuthSpaceMapper;

    @Autowired
    private DocUseSpaceUnitMapper docUseSpaceUnitMapper;

    @Autowired
    private DocUseSpaceConsumerMapper docUseSpaceConsumerMapper;

    @Autowired
    private DocStructTemplateAuthMapper docStructTemplateAuthMapper;

    @Autowired
    private SoidService soidService;


    /**
     * 1、添加结构化模板报告授权空间
     *
     * @param vo 结构化模板报告授权空间Vo
     * @return
     */
    @Override
    public ActionResult add(DocStructTemplateAuthSpaceVo vo) throws Exception {
        log.info("开始添加结构化模板报告授权空间" + vo.toString());
        ActionResult actionResult = new ActionResult();
        if (StringUtils.isBlank(vo.getStTempAuthSpName())) {
            buildBadRequestActionWarn(actionResult, "授权空间名称不能为空");
            return actionResult;
        }
        Integer count = docStructTemplateAuthSpaceMapper.countAuthSpName(vo.getStTempAuthSpName());
        if (count > 0) {
            buildBadRequestActionWarn(actionResult, "授权空间名称已存在");
            return actionResult;
        }
        DocStructTemplateAuthSpace docStructTemplateAuthSpace = new DocStructTemplateAuthSpace();
        BeanUtils.copyProperties(vo, docStructTemplateAuthSpace);
        docStructTemplateAuthSpace.setPyCode(CharTransFormUtil.toPinyinSimple(vo.getStTempAuthSpName()));
        docStructTemplateAuthSpace.setWbCode(CharTransFormUtil.toWubi(vo.getStTempAuthSpName()));

        Long seq = soidService.getSoid();
        docStructTemplateAuthSpace.setStTempAuthSpSoid(seq);
        docStructTemplateAuthSpace.setCreateDate(new Date());
        docStructTemplateAuthSpace.setUpdateDate(new Date());
        docStructTemplateAuthSpace.setIsDelete(0L);
        docStructTemplateAuthSpaceMapper.insert(docStructTemplateAuthSpace);//添加结构化模板报告授权空间基本信息
        //国标
        soidService.insertOid(seq, 4);


        //添加授权空间业务单元数据和授权空间用户数据
        addAuthSpaceUnit(vo, docStructTemplateAuthSpace);
        addAuthSpaceConsumer(vo, docStructTemplateAuthSpace);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    @Override
    public ActionResult  update(DocStructTemplateAuthSpaceVo vo) throws Exception {
        ActionResult actionResult = new ActionResult();

        if (StringUtils.isBlank(vo.getStTempAuthSpSoid().toString())) {
            buildBadRequestActionWarn(actionResult, "授权空间soid不能为空");
            return actionResult;
        }

        if (StringUtils.isBlank(vo.getStTempAuthSpName())) {
            buildBadRequestActionWarn(actionResult, "授权空间soid不能为空");
            return actionResult;
        }

        Integer count = docStructTemplateAuthSpaceMapper.countAuthSpName(vo.getStTempAuthSpName());
        DocStructTemplateAuthSpace docStructTemplateAuthSpace = docStructTemplateAuthSpaceMapper.selectByPrimaryKey(vo.getStTempAuthSpSoid());
        if (count > 0 && !vo.getStTempAuthSpName().equals(docStructTemplateAuthSpace.getStTempAuthSpName())) {
            buildBadRequestActionWarn(actionResult, "授权空间名称已存在");
            return actionResult;
        }
        //1、校验授权空间基本信息是否修改
        if (!(vo.getStTempAuthSpName().equals(docStructTemplateAuthSpace.getStTempAuthSpName())
                && vo.getHospitalSoid().equals(docStructTemplateAuthSpace.getHospitalSoid())
                && vo.getExamServiceType().equals(docStructTemplateAuthSpace.getExamServiceType()))) {//修改了更新
            //1、1更新授权空间基本数据
            docStructTemplateAuthSpace.setStTempAuthSpName(vo.getStTempAuthSpName());
            docStructTemplateAuthSpace.setPyCode(CharTransFormUtil.toPinyinSimple(vo.getStTempAuthSpName()));
            docStructTemplateAuthSpace.setWbCode(CharTransFormUtil.toWubi(vo.getStTempAuthSpName()));
            docStructTemplateAuthSpace.setHospitalSoid(vo.getHospitalSoid());
            docStructTemplateAuthSpace.setGroupSoid(vo.getGroupSoid());
            docStructTemplateAuthSpace.setUpdateDate(new Date());
            docStructTemplateAuthSpace.setExamServiceType(vo.getExamServiceType());
            docStructTemplateAuthSpaceMapper.updateByPrimaryKeySelective(docStructTemplateAuthSpace);
        }

        //2、校验是否修改授权空间业务单元数据
        List<DocUseSpaceUnitVo> sourceUnit = docUseSpaceUnitMapper.findAuthSpSoid(vo.getStTempAuthSpSoid());
        List<DocUseSpaceUnitVo> targetUnit = vo.getDocUseSpaceUnitVoList();
        if (targetUnit != null && targetUnit.size() > 0) {//目标单元不为空
            if (sourceUnit != null && sourceUnit.size() > 0) {//源单元不为空
                if (!targetUnit.equals(sourceUnit)) { //业务单元有修改
                    //1、先删除
                    docUseSpaceUnitMapper.deleteByAuthSpSoid(vo.getStTempAuthSpSoid());
                    //2、添加授权空间业务单元数据
                    addAuthSpaceUnit(vo, docStructTemplateAuthSpace);
                }
            } else {//源单元为空，直接插入
                addAuthSpaceUnit(vo, docStructTemplateAuthSpace);
            }
        } else {//传入的目标单元为空，删除源业务单元
            docUseSpaceUnitMapper.deleteByAuthSpSoid(vo.getStTempAuthSpSoid());
        }

        //3、校验是否修改授权空间用户数据
        List<DocUseSpaceConsumerVo> sourceConsumer = docUseSpaceConsumerMapper.findAuthSpSoid(vo.getStTempAuthSpSoid());
        List<DocUseSpaceConsumerVo> targetConsumer = vo.getDocUseSpaceConsumerVoList();
        if (targetConsumer != null && targetConsumer.size() > 0) {//目标授权空间用户不为空
            if (sourceConsumer != null && targetConsumer.size() > 0) {//源授权空间用户不为空
                if (!targetConsumer.equals(sourceConsumer)) {
                    //1、先删除
                    docUseSpaceConsumerMapper.deleteBySpSoid(vo.getStTempAuthSpSoid());
                    //2、添加授权空间授权空间用户数据
                    addAuthSpaceConsumer(vo, docStructTemplateAuthSpace);
                }
            } else {//源授权空间用户为空，直接插入
                addAuthSpaceUnit(vo, docStructTemplateAuthSpace);
            }
        } else {//传入的目标授权空间用户为空，删除源授权空间用户
            docUseSpaceConsumerMapper.deleteBySpSoid(vo.getStTempAuthSpSoid());
        }


        buildActionSuccess(actionResult);
        return actionResult;
    }


    @Override
    public ActionResult delete(long stTempAuthSpSoid) {
        log.info("开始删除一个授权空间: " + stTempAuthSpSoid);
        ActionResult actionResult = new ActionResult();
        if (StringUtils.isBlank(String.valueOf(stTempAuthSpSoid))) {
            buildBadRequestActionWarn(actionResult, "授权空间soid不能为空");
            return actionResult;
        }
        docStructTemplateAuthSpaceMapper.deleteByPrimaryKey(stTempAuthSpSoid);
        docUseSpaceUnitMapper.deleteByAuthSpSoid(stTempAuthSpSoid);
        docUseSpaceConsumerMapper.deleteBySpSoid(stTempAuthSpSoid);


        buildActionSuccess(actionResult);
        return actionResult;
    }

    @Override
    public ListResult<DocStructTemplateAuthSpaceVo> get(long stTempAuthSpSoid) {
        ListResult<DocStructTemplateAuthSpaceVo> lr = new ListResult<>();
//        DocStructTemplateAuthSpaceVo docStructTemplateAuthSpaceVo = docStructTemplateAuthSpaceMapper.selectByAuthSpSoid(stTempAuthSpSoid);
//        //回显医院名称
//        if (docStructTemplateAuthSpaceVo.getHospitalSoid()!=null) {
//            com.chinatechstar.component.commons.result.ListResult<BaseOrgInfoVo> orgByOrgInfoResult = iOrgInfoApi.findOrgByOrgInfoSoid(docStructTemplateAuthSpaceVo.getHospitalSoid(), false);
//            if (orgByOrgInfoResult.getData()!=null) {
//                docStructTemplateAuthSpaceVo.setHospitalName(orgByOrgInfoResult.getData().getOrgInfoName());
//            }
//        }
//        //回显业务单元名称
//        docStructTemplateAuthSpaceVo.getDocUseSpaceUnitVoList().forEach(vo -> {
//            if (StringUtils.isNotEmpty(vo.getBusinessUnitSoid().toString())) {
//                com.chinatechstar.component.commons.result.ListResult<BusinessUnitVo> businessUnit = iBusinessUnitApi.findBusinessUnitBySoid(vo.getBusinessUnitSoid(), false);
//                if (businessUnit.getData()!=null) {
//                    vo.setBusinessUnitName(businessUnit.getData().getBusinessUnitName());
//                }
//            }
//        });
//        //回显授权人员名称
//        docStructTemplateAuthSpaceVo.getDocUseSpaceConsumerVoList().forEach(vo -> {
//            if (StringUtils.isNotEmpty(vo.getDoctorSoid().toString())) {
//                com.chinatechstar.component.commons.result.ListResult<EmployeeInfoVo> employeeInfoVoListResult = iEmployeeInfoApi.findOneBySoid(vo.getDoctorSoid(), false);
//                if (employeeInfoVoListResult.getData()!=null) {
//                    vo.setEmployeeName(employeeInfoVoListResult.getData().getEmployeeName());
//                }
//            }
//        });
//
//        buildListSuccess(lr, docStructTemplateAuthSpaceVo);
        return lr;
    }

    @Override
    public ListResult<PageResultVo<DocStructTemplateAuthSpaceVo>> findPage(String searChData, Long currentPage, Long pageSize) {
        ListResult result = new ListResult();
        PageResultVo pvo = new PageResultVo();
        Page page = new Page(currentPage, pageSize);
        pvo.setPage(page);
        List<DocStructTemplateAuthSpaceVo> list = null;
        Long pageSt = (currentPage - 1) * pageSize;
        Long pageEd = currentPage * pageSize;
        if (StringUtils.isNotBlank(searChData)) {
            searChData = searChData.toUpperCase();
        }
        Integer count = docStructTemplateAuthSpaceMapper.findPageCount(pageSt, pageEd, searChData);
        if (count != 0) {
            page.setTotalCount(count);
            list = docStructTemplateAuthSpaceMapper.findPage(pageSt, pageEd, searChData);
        } else {
            pvo.setPage(null);
        }
        pvo.setList(list);
        buildListSuccess(result, pvo);
        return result;
    }

    @Override
    public ActionResult checkName(String name, Long stTempAuthSpSoid) {
        ActionResult actionResult = new ActionResult();
        if (StringUtils.isBlank(name)) {
            buildBadRequestActionWarn(actionResult, "授权空间名称不能为空");
            return actionResult;
        }
        Integer count = docStructTemplateAuthSpaceMapper.countAuthSpName(name);
        if (count > 0 && stTempAuthSpSoid == null) {
            buildBadRequestActionWarn(actionResult, "授权空间名称已存在");
            return actionResult;
        }
        DocStructTemplateAuthSpace source = docStructTemplateAuthSpaceMapper.selectByPrimaryKey(stTempAuthSpSoid);
        if (count > 0 && !name.equals(source.getStTempAuthSpName())) {
            buildBadRequestActionWarn(actionResult, "授权空间名称已存在");
            return actionResult;
        }

        buildActionSuccess(actionResult);
        return actionResult;
    }

    @Override
    public ActionResult updateStatus(Long status, Long stTempAuthSpSoid) {
        ActionResult actionResult = new ActionResult();
        if (status == null) {
            buildBadRequestActionWarn(actionResult, "授权空间状态不能为空");
            return actionResult;
        }
        if (stTempAuthSpSoid == null) {
            buildBadRequestActionWarn(actionResult, "授权空间soid不能为空");
            return actionResult;
        }
        Integer countAuth = docStructTemplateAuthMapper.countAuthSpace(stTempAuthSpSoid);
        if (countAuth != 0 && CLOSESTATUS.equals(status)) {
            buildBadRequestActionWarn(actionResult, "授权空间已被引用，不能停用");
            return actionResult;
        }
        //1、更新授权空间状态
        DocStructTemplateAuthSpace docStructTemplateAuthSpace = new DocStructTemplateAuthSpace();
        docStructTemplateAuthSpace.setStTempAuthSpSoid(stTempAuthSpSoid);
        docStructTemplateAuthSpace.setStatus(status);
        docStructTemplateAuthSpace.setUpdateDate(new Date());
        docStructTemplateAuthSpaceMapper.updateByPrimaryKeySelective(docStructTemplateAuthSpace);
        //2、更新关系表状态
        docUseSpaceUnitMapper.updateStatusByAuthSpSoid(status, stTempAuthSpSoid);
        docUseSpaceConsumerMapper.updateStatusByAuthSpSoid(status, stTempAuthSpSoid);


        buildActionSuccess(actionResult);
        return actionResult;
    }

    @Override
    public ListResult<List<DocStructTemplateAuthSpace>> findAll(String searChData,Long hospitalSoid) {
        ListResult result = new ListResult();

        List<DocStructTemplateAuthSpace> all = docStructTemplateAuthSpaceMapper.findAll(searChData.toUpperCase(),hospitalSoid);
        buildListSuccess(result, all);
        return result;
    }

    /**
     * 添加授权空间业务单元数据
     *
     * @param vo                         目标授权空间
     * @param docStructTemplateAuthSpace 源授权空间
     */
    private void addAuthSpaceUnit(DocStructTemplateAuthSpaceVo vo, DocStructTemplateAuthSpace docStructTemplateAuthSpace) {
        //添加授权空间业务单元数据
        List<DocUseSpaceUnitVo> docUseSpaceUnitVoList = vo.getDocUseSpaceUnitVoList();
        DocUseSpaceUnit docUseSpaceUnit = new DocUseSpaceUnit();

        if (!org.springframework.util.StringUtils.isEmpty(docUseSpaceUnitVoList)) {
            for (DocUseSpaceUnitVo docUseSpaceUnitVo : docUseSpaceUnitVoList) {
//                docUseSpaceUnitVo.setUseSpaceUnitSoid(cmoidGanerator.getSOID());
                docUseSpaceUnitVo.setUseSpaceUnitSoid(soidService.getSoid());
                docUseSpaceUnitVo.setStTempAuthSpSoid(docStructTemplateAuthSpace.getStTempAuthSpSoid());
                docUseSpaceUnitVo.setCreateDate(new Date());
                docUseSpaceUnitVo.setUpdateDate(new Date());
                docUseSpaceUnitVo.setIsDelete(0L);
                docUseSpaceUnitVo.setStatus(docStructTemplateAuthSpace.getStatus());
                BeanUtils.copyProperties(docUseSpaceUnitVo, docUseSpaceUnit);
                docUseSpaceUnitMapper.insert(docUseSpaceUnit);
            }
        }
    }

    /**
     * 添加授权空间用户数据
     *
     * @param vo                         目标授权空间
     * @param docStructTemplateAuthSpace 源授权空间
     */
    private void addAuthSpaceConsumer(DocStructTemplateAuthSpaceVo vo, DocStructTemplateAuthSpace docStructTemplateAuthSpace) {
        //添加授权空间用户数据
        List<DocUseSpaceConsumerVo> docUseSpaceConsumerVoList = vo.getDocUseSpaceConsumerVoList();
        DocUseSpaceConsumer docUseSpaceConsumer = new DocUseSpaceConsumer();
        if (!org.springframework.util.StringUtils.isEmpty(docUseSpaceConsumerVoList)) {
            for (DocUseSpaceConsumerVo docUseSpaceConsumerVo : docUseSpaceConsumerVoList) {
//                docUseSpaceConsumerVo.setSpaceConsumerSoid(cmoidGanerator.getSOID());
                docUseSpaceConsumerVo.setSpaceConsumerSoid(soidService.getSoid());
                docUseSpaceConsumerVo.setStTempAuthSpSoid(docStructTemplateAuthSpace.getStTempAuthSpSoid());
                docUseSpaceConsumerVo.setIsDelete(0L);
                docUseSpaceConsumerVo.setStatus(docStructTemplateAuthSpace.getStatus());
                docUseSpaceConsumerVo.setUpdateDate(new Date());
                docUseSpaceConsumerVo.setCreateDate(new Date());
                BeanUtils.copyProperties(docUseSpaceConsumerVo, docUseSpaceConsumer);
                docUseSpaceConsumerMapper.insert(docUseSpaceConsumer);
            }
        }
    }

    /**
     * 11、根据授权空间soid查询授权空间基本信息
     *
     * @param stTempAuthSpSoid 授权空间soid
     * @return 授权空间基本信息
     */
    @Override
    public ListResult<DocStructTemplateAuthSpaceVo> selectByAuthSpSoid(long stTempAuthSpSoid) {
        log.info("开始根据授权空间soid查询授权空间基本信息,查询条件:" + stTempAuthSpSoid);
        StopWatch stopWatch = StopWatch.createStarted();
        ListResult<DocStructTemplateAuthSpaceVo> listResult = new ListResult<>();
        if (StringUtils.isEmpty(String.valueOf(stTempAuthSpSoid))) {
            buildBadRequestListWarn(listResult, "授权空间soid不能为空");
        }
        try {
            //获取定义空间
            DocStructTemplateAuthSpaceVo docStructTemplateAuthSpaceVo = docStructTemplateAuthSpaceMapper.selectByAuthSpSoid(stTempAuthSpSoid);
            buildListSuccess(listResult, docStructTemplateAuthSpaceVo);
        } catch (Exception e) {
            log.error("根据授权空间soid查询授权空间基本信息异常", e);
            buildListWarn(listResult, "根据授权空间soid查询授权空间基本信息失败");
        } finally {
            stopWatch.stop();
            log.info("本次查询耗时:" + stopWatch.getTime() + "ms");
        }
        return listResult;
    }

    /**
     * 批量插入模板授权空间业务处理
     *
     * @param listDocStructTemplateAuth
     * @return
     * @throws Exception
     */
    @Override
    public ActionResult addDocStructTemplateAuthBatch(List<DocStructTemplateAuth> listDocStructTemplateAuth) throws Exception {
        ActionResult actionResult = new ActionResult();
        List<Long> listSoid = soidService.getSoids(listDocStructTemplateAuth.size());
        DocStructTemplateAuth docStructTemplateAuth;
        for (int i = 0; i < listDocStructTemplateAuth.size(); i++) {
            docStructTemplateAuth = new DocStructTemplateAuth();
            docStructTemplateAuth = listDocStructTemplateAuth.get(i);
            docStructTemplateAuth.setStTempAuthSoid(listSoid.get(i));
        }
        docStructTemplateAuthMapper.addDocStructTemplateAuthBatch(listDocStructTemplateAuth);
        buildActionSuccess(actionResult);
        return actionResult;
    }
}
